<template>
  <div class="login">
    <h2>登录</h2>
    <form @submit.prevent="doLogin">
      <!--    <form method="post" action="/api/user/doLogin">-->
      <p class="form-item">
        <label for="username">用户名:</label>
        <input type="text" placeholder="用户名" name="username" v-model="username" required>
      </p>
      <p class="form-item">
        <label for="password">密码:</label>
        <input type="password" placeholder="密码" name="password" v-model="password" required>
      </p>
      <button class="login-button" type="submit">登录</button>
      <button class="login-button" type="button" @click="geolocation">测试</button>
    </form>
  </div>
</template>

<script setup>

import {ref} from "vue";
import router from "@/router/index.js";
/**
 * 测试
 */

function geolocation() {
  console.log(666)
  // console.log(navigator.geolocation)
  // if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
      console.log(position.coords.longitude)
      console.log(position.coords.latitude)
    })
  // }else{
  //   alert("浏览器不支持Geolocation API")
  // }
}

/**
 向后端发起登录请求并处理后端响应
 */
let username = ref('')
let password = ref('')

//向后端发起登录请求的函数
function doLogin() {

  //构建formDate,浏览器原生提供的API函数fetch，以便于后端的Security框架能够正确处理登录请求
  let formData = new FormData();
  formData.append('username', username.value)
  formData.append('password', password.value)
  fetch('/api/user/doLogin', {
    method: 'POST',
    body: formData
  })
      .then(response => response.json())
      .then(data => {
        console.log(data);
        if(data.code === 200){
          console.log("欢迎登录")
          router.push("/")
        }
      })
      .catch(error => {
        console.log(error)
      })
}
</script>

<style scoped lang="less">
.login {
  max-width: 400px;
  margin: 250px auto;
  padding: 10px 10px 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
}

h2 {
  margin: 10px;
}

.form-item {
  height: 50px;
  width: 270px;
  display: flex;
  align-items: center;

  label {
    width: 25%;
    margin-right: 20px;
  }

  input {
    width: 75%;
    background-color: var(--background);
    margin-top: 2%;
    color: var(--color);
    height: 30px;
  }

  .login-button {
    width: 200px;
  }
}
</style>
